package cn.getech.data.metadata.service.impl;

import cn.getech.data.development.constant.ConnectTypeEnum;
import cn.getech.data.development.constant.PermissionTypeEnum;
import cn.getech.data.development.entity.ConfConnect;
import cn.getech.data.development.entity.ScheduleTimeDeleteEntity;
import cn.getech.data.development.entity.ScheduleTimeEntity;
import cn.getech.data.development.service.ConfConnectService;
import cn.getech.data.development.service.ScheduleTimeDeleteService;
import cn.getech.data.development.service.ScheduleTimeService;
import cn.getech.data.development.utils.DataPermissionUtil;
import cn.getech.data.intelligence.common.exception.RRException;
import cn.getech.data.intelligence.common.utils.DateUtils;
import cn.getech.data.intelligence.common.utils.PageUtils;
import cn.getech.data.intelligence.common.utils.PageUtils2;
import cn.getech.data.metadata.constant.TaskStatusEnum;
import cn.getech.data.metadata.constant.WeekEnum;
import cn.getech.data.metadata.constant.YesOrNoEnum;
import cn.getech.data.metadata.entity.CollectionNotificationUser;
import cn.getech.data.metadata.entity.CollectionTaskCategory;
import cn.getech.data.metadata.entity.CollectionTaskScheduleConfigEntity;
import cn.getech.data.metadata.entity.meta.CollectionNotificationRelatednessUser;
import cn.getech.data.metadata.entity.meta.CollectionTask;
import cn.getech.data.metadata.handler.TaskExecuteHandler;
import cn.getech.data.metadata.mapper.CollectionTask2Mapper;
import cn.getech.data.metadata.mapper.CollectionTaskCategoryMapper;
import cn.getech.data.metadata.model.req.collectiontask.CollectionTaskAutoSaveReq;
import cn.getech.data.metadata.model.req.collectiontask.CollectionTaskAutoUpdateReq;
import cn.getech.data.metadata.model.req.collectiontask.CollectionTaskRunReq;
import cn.getech.data.metadata.model.req.meta.CollectionTaskListReq;
import cn.getech.data.metadata.model.res.CollectionTaskAutoInfoRes;
import cn.getech.data.metadata.model.res.CollectionTaskListRes;
import cn.getech.data.metadata.service.CollectionNotificationRelatednessUserService;
import cn.getech.data.metadata.service.CollectionTask2Service;
import cn.getech.data.metadata.service.CollectionTaskScheduleConfigService;
import cn.getech.data.metadata.utils.CronUtils;
import cn.getech.system.center.entity.SysRoleEntity;
import cn.getech.system.center.service.SysRoleService;
import cn.getech.system.center.utils.ShiroUtils;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

@Service("collectionTask2ServiceImpl")
public class CollectionTask2ServiceImpl extends ServiceImpl<CollectionTask2Mapper, CollectionTask> implements CollectionTask2Service {
    @Autowired
    private CollectionTaskScheduleConfigService collectionTaskScheduleConfigService;

    @Autowired
    private ScheduleTimeService scheduleTimeService;
    @Autowired
    private ScheduleTimeDeleteService scheduleTimeDeleteService;
    @Autowired
    private TaskExecuteHandler taskExecuteHandler;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private ConfConnectService confConnectService;
    @Autowired
    private CollectionNotificationRelatednessUserService collectionNotificationRelatednessUserService;
    @Autowired
    private CollectionTaskCategoryMapper collectionTaskCategoryMapper;

    @Override
    public void saveAutoTask(CollectionTaskAutoSaveReq req) {
        req.setOwnModule(-1);
        if(req.getTaskName().length() > 15){
            throw new RRException("任务名称长度不能超过15个字符");
        }
        Integer tenantId = ShiroUtils.getTenantId();
        Integer count = baseMapper.selectCount(
                new QueryWrapper<CollectionTask>()
                        .eq("task_name", req.getTaskName())
                        .eq(tenantId != null, "tenant_id", tenantId)
                        .eq("delete_flag", YesOrNoEnum.NO.getValue())
        );
        if(count > 0)
            throw new RRException("已经存在该任务名称，请使用其他任务名称");

        ConfConnect confConnect = confConnectService.getById(req.getSourceId());
        if(confConnect == null)
            throw new RRException("没有该数据源");

        try {
            //自动采集任务，需要校验配置的数据库是否已经被其他采集任务配置了
            if(req.getTaskType()!=null&&req.getTaskType()==1) {
                checkDbName(null, confConnect, req.getDbNames(),tenantId);
            }
        } catch (Exception e) {
            throw new RRException(e.getMessage());
        }

        if(req.getScheduleEnable().intValue() == 1){
            if(req.getScheduleMode().intValue() == 1){//1:间隔 2:定时
                if(req.getIntervalValue() == null){
                    throw new RRException("调度周期值不能为空");
                } else if(req.getIntervalValue().intValue() <= 0){
                    throw new RRException("调度周期值要大于0");
                }
            } else {
                if(req.getScheduleDay() == null && req.getScheduleHour() == null &&  req.getScheduleMinute() == null){
                    throw new RRException("调度周期值不能为空");
                }
            }
        }

        CollectionTask task = new CollectionTask();
        task.setTenantId(tenantId);
        task.setTaskName(req.getTaskName());
        task.setTaskType(req.getTaskType());
        task.setOwnSystem(req.getOwnSystem());
        task.setOwnModule(req.getOwnModule());
        task.setSourceType(req.getSourceType());
        task.setSourceId(req.getSourceId());
        task.setRunEnable(0);//是否启用 0 未启用 1 启用
        task.setRunCount(0);
        task.setCreateTime(new Date());
        task.setCreateUser(ShiroUtils.getUserId());
        task.setUpdateTime(task.getCreateTime());
        task.setUpdateUser(task.getCreateUser());
        task.setDeleteFlag(0);//删除 1 是,0 否
        task.setRunStatus(TaskStatusEnum.NONE.getValue());
        task.setInitRole(req.getInitRole());
        StringBuilder str = new StringBuilder();
        req.getDbNames().stream().forEach(db -> {
            str.append(db).append(",");
        });
        String dbName = str.substring(0, str.length() - 1);
        task.setDbName(dbName);

        CollectionTaskScheduleConfigEntity configEntity = new CollectionTaskScheduleConfigEntity();
        wrapCorn(task, configEntity, req.getScheduleEnable(), req.getScheduleMode(),
                req.getScheduleUnit(), req.getIntervalValue(), req.getScheduleMinute(),
                req.getScheduleHour(), req.getScheduleDay());

        baseMapper.insert(task);
        //修改采集任务的所属目录
        collectionTaskCategoryMapper.delete(new QueryWrapper<CollectionTaskCategory>().eq("task_id",task.getId()));
        if(req.getCategoryIdsList()!=null){
            for(String key:req.getCategoryIdsList()){
                CollectionTaskCategory taskCategory = new CollectionTaskCategory();
                taskCategory.setCategoryId(Integer.valueOf(key));
                taskCategory.setTaskId(task.getId().intValue());
                taskCategory.setCreateId(ShiroUtils.getUserId().intValue());
                taskCategory.setTenantId(ShiroUtils.getTenantId());
                taskCategory.setCreateTime(new Date());
                collectionTaskCategoryMapper.insert(taskCategory);
            }
        }
        configEntity.setTaskId(task.getId());
        collectionTaskScheduleConfigService.save(configEntity);
        //关联用户通知组保存
        if(CollectionUtil.isNotEmpty(req.getUserGroupNameId())){
            for(Long userGroupId:req.getUserGroupNameId()){
                CollectionNotificationRelatednessUser collectionNotificationRelatednessUser = new CollectionNotificationRelatednessUser();
                collectionNotificationRelatednessUser.setUpdateTime(new Date());
                collectionNotificationRelatednessUser.setCreateTime(new Date());
                collectionNotificationRelatednessUser.setCollectionNotificationUserId(userGroupId);
                collectionNotificationRelatednessUser.setCollectionRelatednessId(task.getId());
                collectionNotificationRelatednessUser.setRelatednessType("1");
                collectionNotificationRelatednessUser.setUpdateUser(ShiroUtils.getUserId());
                collectionNotificationRelatednessUser.setCreateUser(ShiroUtils.getUserId());
                collectionNotificationRelatednessUserService.saveRelatednessNotification(collectionNotificationRelatednessUser);
            }
        }
    }

    private void wrapCorn(CollectionTask task, CollectionTaskScheduleConfigEntity configEntity,
                          Integer scheduleEnable, Integer scheduleMode,
                          Integer scheduleUnit, Integer intervalValue,
                          Integer scheduleMinute, Integer scheduleHour,
                          Integer scheduleDay) {
        configEntity.setScheduleEnable(scheduleEnable);
        configEntity.setScheduleMode(scheduleMode);
        configEntity.setScheduleUnit(scheduleUnit);
        configEntity.setScheduleId("");

        if(WeekEnum.Mon.getValue().equals(scheduleEnable)){
            String value = "";
            if(WeekEnum.Mon.getValue().equals(scheduleMode)){//1:间隔 2:定时
                value = intervalValue + "";
            } else if(WeekEnum.Tue.getValue().equals(scheduleMode)){
                int minute = scheduleMinute == null ? 0 : scheduleMinute;
                int hour = scheduleHour == null ? 0 : scheduleHour;
                int day = scheduleDay == null ? 0 : scheduleDay;
                switch (scheduleUnit) {
                    case 3:
                        value = minute + "";
                        break;
                    case 4:
                        value = minute + " " + hour;
                        break;
                    case 5:
                    case 6:
                        value = minute + " " + hour + " " + day;
                        break;
                }
            }
            configEntity.setScheduleUnitValue(value);
            String cron = CronUtils.getCronExpression(configEntity.getScheduleUnit(), configEntity.getScheduleUnitValue());
            configEntity.setScheduleCron(cron);
            String runPlan = CronUtils.getCronDescription(configEntity.getScheduleUnit(), configEntity.getScheduleUnitValue());
            task.setRunPlan(runPlan);
        } else {
            configEntity.setScheduleUnitValue("");
            configEntity.setScheduleCron("");
            task.setRunPlan("按需采集");
        }
    }

    @Override
    public void updateAutoTask(CollectionTaskAutoUpdateReq req) {
        if(req.getTaskName().length() > 15){
            throw new RRException("任务名称长度不能超过15个字符");
        }
        CollectionTask oldTask = baseMapper.selectOne(
                new QueryWrapper<CollectionTask>()
                        .eq("id", req.getTaskId())
        );
        if(oldTask == null)
            throw new RRException("不存在该任务id");
        if(oldTask.getRunStatus().intValue() == TaskStatusEnum.RUNNING.getValue().intValue()){
            throw new RRException("任务正在运行，不能编辑任务");
        }
        Integer tenantId = ShiroUtils.getTenantId();
        Integer count = baseMapper.selectCount(
                new QueryWrapper<CollectionTask>()
                        .eq("task_name", req.getTaskName())
                        .eq(tenantId != null, "tenant_id", tenantId)
                        .eq("delete_flag",  YesOrNoEnum.NO.getValue())
                        .ne("id", req.getTaskId())
        );
        if(count > 0)
            throw new RRException("已经存在该任务名称，请使用其他任务名称");

        ConfConnect confConnect = confConnectService.getById(req.getSourceId());
        try {
            //自动采集任务，需要校验配置的数据库是否已经被其他采集任务配置了
            if(req.getTaskType()!=null&&req.getTaskType()==1){
                checkDbName(req.getTaskId(),confConnect,req.getDbNames(), tenantId);
            }
        } catch (Exception e) {
            throw new RRException(e.getMessage());
        }

        if(req.getScheduleEnable().intValue() == 1){
            if(req.getScheduleMode().intValue() == 1){//1:间隔 2:定时
                if(req.getIntervalValue() == null){
                    throw new RRException("调度周期值不能为空");
                } else if(req.getIntervalValue().intValue() <= 0){
                    throw new RRException("调度周期值要大于0");
                }
            } else {
                if(req.getScheduleDay() == null && req.getScheduleHour() == null &&  req.getScheduleMinute() == null){
                    throw new RRException("调度周期值不能为空");
                }
            }
        }

        CollectionTask task = new CollectionTask();
        task.setId(req.getTaskId());
        task.setTaskName(req.getTaskName());
        task.setTaskType(req.getTaskType());
        task.setOwnSystem(req.getOwnSystem());
        task.setOwnModule(req.getOwnModule());
        task.setSourceType(req.getSourceType());
        task.setSourceId(req.getSourceId());
        task.setUpdateTime(new Date());
        task.setUpdateUser(ShiroUtils.getUserId());
        task.setTaskLeader(task.getUpdateUser());
        task.setInitRole(req.getInitRole());
        StringBuilder str = new StringBuilder();
        req.getDbNames().stream().forEach(db -> {
            str.append(db).append(",");
        });
        String dbName = str.substring(0, str.length() - 1);
        task.setDbName(dbName);

        CollectionTaskScheduleConfigEntity configEntity = collectionTaskScheduleConfigService.getById(task.getId());
        if (configEntity == null) {
            configEntity = new CollectionTaskScheduleConfigEntity();
        }
        configEntity.setTaskId(task.getId());
        wrapCorn(task, configEntity, req.getScheduleEnable(),
                req.getScheduleMode(), req.getScheduleUnit(),
                req.getIntervalValue(), req.getScheduleMinute(), req.getScheduleHour(), req.getScheduleDay());


        if(WeekEnum.Tue.getValue().equals(configEntity.getScheduleEnable())) {//调度方式 1:正常 2:暂停
            String scheduleId = "1_"+task.getTaskName()+"_"+task.getId();
            ScheduleTimeDeleteEntity deleteEntity = new ScheduleTimeDeleteEntity();
            deleteEntity.setScheduleId(scheduleId);
            deleteEntity.setScheduleType(2);//类型 1:邮件 2:元数据采集
            scheduleTimeDeleteService.saveOrUpdate(deleteEntity);
            scheduleTimeService.removeById(scheduleId);
        }
        task.setRunEnable(0);
        baseMapper.updateById(task);
        //修改采集任务的所属目录
        collectionTaskCategoryMapper.delete(new QueryWrapper<CollectionTaskCategory>().eq("task_id",task.getId()));
        if(req.getCategoryIdsList()!=null){
            for(String key:req.getCategoryIdsList()){
                CollectionTaskCategory taskCategory = new CollectionTaskCategory();
                taskCategory.setCategoryId(Integer.valueOf(key));
                taskCategory.setTaskId(task.getId().intValue());
                taskCategory.setCreateId(ShiroUtils.getUserId().intValue());
                taskCategory.setTenantId(ShiroUtils.getTenantId());
                taskCategory.setCreateTime(new Date());
                collectionTaskCategoryMapper.insert(taskCategory);
            }
        }
        collectionTaskScheduleConfigService.updateById(configEntity);
        if(CollectionUtil.isNotEmpty(req.getUserGroupNameId())) {
            ArrayList<CollectionNotificationRelatednessUser> collectionNotificationRelatednessUsers=new ArrayList<>();
            for(Long userGroupId:req.getUserGroupNameId()){
                CollectionNotificationRelatednessUser collectionNotificationRelatednessUser = new CollectionNotificationRelatednessUser();
                collectionNotificationRelatednessUser.setUpdateTime(new Date());
                collectionNotificationRelatednessUser.setCollectionNotificationUserId(userGroupId);
                collectionNotificationRelatednessUser.setCollectionRelatednessId(req.getTaskId());
                collectionNotificationRelatednessUser.setRelatednessType("1");
                collectionNotificationRelatednessUser.setUpdateUser(ShiroUtils.getUserId());
                collectionNotificationRelatednessUser.setCreateUser(ShiroUtils.getUserId());
                collectionNotificationRelatednessUsers.add(collectionNotificationRelatednessUser);
            }
            collectionNotificationRelatednessUserService.updateRelatednessNotification(collectionNotificationRelatednessUsers,req.getTaskId(),"1");
        }else{
            collectionNotificationRelatednessUserService.updateRelatednessNotification(new ArrayList<>(),req.getTaskId(),"1");
        }
    }

    /**
    * @Description 检查配置的数据库是否已经被其他采集任务配置
    * @Author  chengweiping
    * @Date   2021/1/25 11:56
    */
    public void checkDbName(Long taskId, ConfConnect confConnect, List<String> dbNameList, Integer tenantId) throws Exception{

        ConnectTypeEnum t = ConnectTypeEnum.ObjOf(confConnect.getTypeId());
        List<CollectionTask>  collectionTaskList=null;
        if(taskId!=null&&taskId>0){
            //先获取排除本身任务下的其他字段任务的数据源ID,如果是更新采集任务时查询时,增加任务ID不等于自己
             collectionTaskList= baseMapper.selectList(
                    new QueryWrapper<CollectionTask>()
                            .eq("delete_flag",  YesOrNoEnum.NO.getValue())
                            .eq("task_type",1)
                            .eq("tenant_id",tenantId)
                            .ne("id", taskId));
        }else{
            //先获取排除本身任务下的其他字段任务的数据源ID
               collectionTaskList= baseMapper.selectList(
                    new QueryWrapper<CollectionTask>()
                            .eq("delete_flag",  YesOrNoEnum.NO.getValue())
                            .eq("tenant_id",tenantId)
                            .eq("task_type",1));
        }

        if(CollectionUtil.isEmpty(collectionTaskList)){
             return;
        }
        for(String dbName : dbNameList){
            //循环检查本次添加的采集任务的,每个数据库是否已经存在对应任务了  去重还得加上用户id
            String sourceConf = t.getUrl().replace("<host>", confConnect.getHost()).replace("<port>", confConnect.getPort()).replace("<db_name>", dbName);
            sourceConf = sourceConf + confConnect.getUsername();
            for(CollectionTask collectionTask:collectionTaskList){
                ConfConnect  checkConfConnect = confConnectService.getById(collectionTask.getSourceId());
                String dbNames=collectionTask.getDbName();
                if(checkConfConnect!=null&&StringUtils.isNotBlank(dbNames)){
                    String[]  dbNameArr=dbNames.split(",");
                    for(String checkDbname:dbNameArr){
                        //循环检查本次添加的采集任务的,每个数据库是否已经存在对应任务了
                        String checkSourceConf = t.getUrl().replace("<host>", checkConfConnect.getHost()).replace("<port>", checkConfConnect.getPort()).replace("<db_name>", checkDbname);
                        checkSourceConf = checkSourceConf + checkConfConnect.getUsername();
                        if(checkSourceConf.equals(sourceConf)){
                            throw new RRException(String.format("该数据源数据库%s,已经被采集任务[%s]配置", dbName,collectionTask.getTaskName()));
                        }
                    }
                }

            }


        }


    }

    @Override
    public void run(CollectionTaskRunReq req) {
        CollectionTask task = baseMapper.selectById(req.getTaskId());
        if(task == null)
            throw new RRException("任务没有该记录");

        if(task.getRunStatus().intValue() == TaskStatusEnum.RUNNING.getValue().intValue()){
            throw new RRException("任务正在运行当中");
        }

        CollectionTaskScheduleConfigEntity configEntity = collectionTaskScheduleConfigService.getById(task.getId());
        if(configEntity == null)
            throw new RRException("任务配置没有该记录");

        CollectionTask updateTask = new CollectionTask();
        updateTask.setId(task.getId());
        updateTask.setTaskRunLeader(ShiroUtils.getUserId());
        updateTask.setRunStatus(TaskStatusEnum.RUNNING.getValue());
        baseMapper.updateById(updateTask);

        oneExecute(task.getId());
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void oneExecute(Long taskId){
        CountDownLatch latch = new CountDownLatch(1);
        try {
            taskExecuteHandler.oneExecute(taskId + "", (res) ->{
                latch.countDown();
            });
        } catch (Exception e) {
            latch.countDown();
            throw new RRException("任务运行异常");
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RRException("任务运行异常");
        }
    }

  @Override
    public void stop(CollectionTaskRunReq req) {
        CollectionTask task = baseMapper.selectById(req.getTaskId());
        if(task == null)
            throw new RRException("任务没有该记录");

        if(task.getRunStatus().intValue() != TaskStatusEnum.RUNNING.getValue().intValue()){
            throw new RRException("任务状态不是运行状态");
        }

        taskExecuteHandler.oneStop();

        CollectionTask updateTask = new CollectionTask();
        updateTask.setId(task.getId());
        updateTask.setTaskRunLeader(ShiroUtils.getUserId());
        updateTask.setRunStatus(TaskStatusEnum.FAIL.getValue());
        baseMapper.updateById(updateTask);
    }

    @Override
    public void enableOrDisable(CollectionTaskRunReq req) {
        CollectionTask task = baseMapper.selectById(req.getTaskId());
        if(task == null)
            throw new RRException("任务没有该记录");

        CollectionTask updateTask = new CollectionTask();
        updateTask.setId(task.getId());
        updateTask.setUpdateTime(new Date());
        updateTask.setUpdateUser(ShiroUtils.getUserId());

        if(ObjectUtils.equals(task.getRunEnable(), 0)){//是否启用 0 未启用 1 启用
            ////自动
            if(ObjectUtils.equals(task.getTaskType(),1)){
                CollectionTaskScheduleConfigEntity configEntity = collectionTaskScheduleConfigService.getById(task.getId());
                if(configEntity == null)
                    throw new RRException("任务配置没有该记录");

                String scheduleId = "1_"+task.getTaskName()+"_"+task.getId();

                ScheduleTimeEntity scheduleTimeEntity = scheduleTimeService.getById(scheduleId);
                if(scheduleTimeEntity == null){
                    scheduleTimeEntity = new ScheduleTimeEntity();
                    scheduleTimeEntity.setScheduleId(scheduleId);
                }
                Date scheduleTime = scheduleTimeService.getCronNextDate(new Date(), configEntity.getScheduleCron());
                if(scheduleTime == null){
                    throw new RRException("当前配置不是有效时间，请配置其他时间");
                }
                scheduleTimeEntity.setCron(configEntity.getScheduleCron());
                scheduleTimeEntity.setScheduleTime(scheduleTime.getTime());
                scheduleTimeEntity.setScheduleTimeStr(DateUtils.format(scheduleTime, DateUtils.DATE_TIME_PATTERN));
                scheduleTimeEntity.setBeanName("taskExecuteHandler");
                scheduleTimeEntity.setFunction("execute");
                scheduleTimeEntity.setParams(""+task.getId());
                scheduleTimeEntity.setScheduleType(2);//类型 1:邮件 2:元数据采集
                scheduleTimeEntity.setCreateTime(new Date());
                scheduleTimeService.saveOrUpdate(scheduleTimeEntity);

                configEntity.setScheduleId(scheduleId);
                collectionTaskScheduleConfigService.updateById(configEntity);

                updateTask.setTaskRunLeader(ShiroUtils.getUserId());
            }

            updateTask.setRunEnable(1);
        } else {
            if(ObjectUtils.equals(task.getTaskType(),1)) {//自动
                CollectionTaskScheduleConfigEntity configEntity = collectionTaskScheduleConfigService.getById(task.getId());
                if(configEntity == null)
                    throw new RRException("任务配置没有该记录");

                ScheduleTimeDeleteEntity deleteEntity = new ScheduleTimeDeleteEntity();
                deleteEntity.setScheduleId(configEntity.getScheduleId());
                deleteEntity.setScheduleType(2);//类型 1:邮件 2:元数据采集
                scheduleTimeDeleteService.saveOrUpdate(deleteEntity);
                scheduleTimeService.removeById(configEntity.getScheduleId());
            }

            updateTask.setRunEnable(0);
        }

        baseMapper.updateById(updateTask);
    }

    @Override
    public CollectionTaskAutoInfoRes info(CollectionTaskRunReq req) {
        CollectionTask task = baseMapper.selectById(req.getTaskId());
        if(task == null)
            throw new RRException("任务没有该记录");

        CollectionTaskScheduleConfigEntity configEntity = collectionTaskScheduleConfigService.getById(task.getId());
        if(configEntity == null)
            throw new RRException("任务配置没有该记录");

        CollectionTaskAutoInfoRes res = new CollectionTaskAutoInfoRes();
        res.setTaskId(task.getId());
        res.setTaskName(task.getTaskName());
        res.setTaskType(task.getTaskType());
        res.setOwnSystem(task.getOwnSystem());
        res.setOwnModule(task.getOwnModule());
        res.setSourceType(task.getSourceType());
        res.setSourceId(task.getSourceId());
        res.setScheduleEnable(configEntity.getScheduleEnable());
        res.setScheduleMode(configEntity.getScheduleMode());
        res.setScheduleUnit(configEntity.getScheduleUnit());
        res.setInitRole(task.getInitRole());
        //查询用户通知组列表
        List<CollectionNotificationUser> collectionNotificationUsers = collectionNotificationRelatednessUserService.queryCollectionNotificationRelatednessUserId(task.getId(), "1");
        res.setCollectionNotificationUsers(collectionNotificationUsers);
        if(StringUtils.isNotEmpty(task.getDbName())){
            String[] dbNames = task.getDbName().split(",");
            List<String> dbList = new ArrayList<>();
            CollectionUtil.addAll(dbList, dbNames);
            res.setDbNames(dbList);
        }
        SysRoleEntity roleEntity = sysRoleService.getById(task.getInitRole());
        if(roleEntity != null){
            res.setRoleName(roleEntity.getRoleName());
        }

        if(StringUtils.isNotEmpty(configEntity.getScheduleUnitValue())){
            if(res.getScheduleMode().intValue() == 1){
                res.setIntervalValue(Integer.parseInt(configEntity.getScheduleUnitValue()));
            } else {
                String[] split = configEntity.getScheduleUnitValue().split(" ");
                try {
                    res.setScheduleMinute(Integer.parseInt(split[0]));
                } catch (NumberFormatException ignored) {
                }
                if (split.length >= 2) {
                    try {
                        res.setScheduleHour(Integer.parseInt(split[1]));
                    } catch (NumberFormatException ignored) {

                    }
                }
                if (split.length == 3) {
                    try {
                        res.setScheduleDay(Integer.parseInt(split[2]));
                    } catch (NumberFormatException ignored) {
                    }
                }
            }
        }
        return res;
    }

    @Override
    public PageUtils2<CollectionTaskListRes> listBy(CollectionTaskListReq req) {
        Map<String, Object> params = new HashMap<>();
        if(StringUtils.isNotEmpty(req.getTaskName()))
            params.put("taskName", req.getTaskName());
        if(req.getTaskType() != null)
            params.put("taskType", req.getTaskType());
        if(req.getId() != null)
            params.put("id", req.getId());
        if (req.getLimit() != null && req.getPage() != null) {
            params.put("offset", (req.getPage() - 1) * req.getLimit());
            params.put("limit", req.getLimit());
        }
        if(req.getCreatePer()!=null){
            params.put("createPer", req.getCreatePer());
        }
        Integer tenantId = ShiroUtils.getTenantId();
        params.put("tenantId", tenantId);
        List<CollectionTaskListRes> list = baseMapper.listBy(params);
        if(CollectionUtils.isNotEmpty(list)){
            for(CollectionTaskListRes collectionTask:list){
                List<CollectionNotificationUser> collectionNotificationUsers = collectionNotificationRelatednessUserService.queryCollectionNotificationRelatednessUserId(collectionTask.getId(), "1");
                collectionTask.setCollectionNotificationUsers(collectionNotificationUsers);
                List<Integer> cateIdList = baseMapper.selectCategoryIds(collectionTask.getId().intValue());
                List<String> cateNameList = new ArrayList<>();
                if(cateIdList.size()>0){
                    cateNameList = baseMapper.selectCategoryNames(cateIdList);
                }
                List<String> cateIdStrList = new ArrayList<>();
                for(Integer cateId:cateIdList){
                    cateIdStrList.add(cateId.toString());
                }
                collectionTask.setCategoryIdsList(cateIdStrList);
                collectionTask.setCategoryNamesList(cateNameList);
            }
        }
        Integer count = baseMapper.listByCount(params);
        //设置采集任务权限标识
        setCollectionTaskListResAuth(list);
        PageUtils2<CollectionTaskListRes> pageUtils = new PageUtils2(list, count, req.getLimit(), req.getPage());
        return pageUtils;
    }

    @Override
    public List<Map<String,Object>> userListBy(){
        Integer tenantId = ShiroUtils.getTenantId();
        return baseMapper.userListBy(tenantId);
    }



    /**
    * @Description 设置采集任务权限标识
    * @Author  chengweiping
    * @Date   2021/1/25 10:24
    */
    public void  setCollectionTaskListResAuth(List<CollectionTaskListRes>  list){
        if(CollectionUtil.isEmpty(list)){
            return ;
        }
        List<Integer> confConnectIdList=DataPermissionUtil.getDataIds(ShiroUtils.getUserId().intValue(),
                PermissionTypeEnum.RESOURCE.getType(), PermissionTypeEnum.QUERY.getType());
        if(CollectionUtil.isEmpty(confConnectIdList)){
            //没有数据源则自动任务没有权限，其他任务有权限
            list.stream().forEach(e->{
                if(e.getTaskType()!=null&&e.getTaskType().equals(1)){
                     e.setHasAuth(0);
                }else{
                    e.setHasAuth(1);
                }
            });
        }else{
            for (CollectionTaskListRes collectionTaskListRes : list) {
                //如果是自动任务，则判断自动任务配置的数据源是否在拥有的数据源权限中
                if (collectionTaskListRes.getTaskType() != null && collectionTaskListRes.getTaskType().equals(1)) {
                    Integer sourceId = collectionTaskListRes.getSourceId();
                    if (confConnectIdList.contains(sourceId)) {
                        collectionTaskListRes.setHasAuth(1);
                    } else {
                        //不包含在拥有的数据源列表中，则无权限
                        collectionTaskListRes.setHasAuth(0);
                    }

                } else {
                    //其他类型的数据统一设置为拥有权限
                    collectionTaskListRes.setHasAuth(1);
                }

            }
        }


    }

}
